package com.ruoyi.web.core.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.service.*;
import com.ruoyi.framework.aspectj.LogAspect;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: sy
 * @Date: Created by 2021/7/9 15:34
 * @description:
 */
@Component
//@RocketMQMessageListener( topic = "bac_fee_record", consumerGroup = "bzba_extend_yz_group", accessKey = "rocketmq2", secretKey = "12345678")
public class KafkaConsumer  {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
    @Autowired
    private ILedyBacFeeService ledyBacFeeService;
    @Autowired
    private ILedyUserClientService userClientService;
    @Autowired
    private ILedyFeeCheckinService checkinService;
    @Autowired
    private ILedyFeeRefundService refundService;
    @Autowired
    private ILedyOuterFeeCollectService collectService;
    @Autowired
    private ILedyOuterFeePayService payService;
    @Autowired
    private ILedyUserSimpleService simpleService;
    @Autowired
    private ISysOperLogService logService;
    @Autowired
    private ICustomerService customerService;

    /**
     * topics 可配置多个 topic
     */
//    @Override
    public void onMessage(String message) {
        System.out.println("接收到消息：" + message);
        try {
            jsonParse(message);
            addLog(message, "bac_fee_record", 0, null);
        } catch (Exception e) {
            log.error("异常信息:{}", e.toString());
            addLog(message, "bac_fee_record", 1, e.toString());
        }
        // 业务逻辑处理（成功返回 CONSUME_SUCCESS，失败返回 RECONSUME_LATER[3](@ref)）
        log.error("异常信息:{}", message);
    }

    //    @Log(title = "kafka bac_fee_record")
//    @KafkaListener(topics = "bac_fee_record", groupId = "testGroup")
//    @KafkaListener(topics = "bac_fee_record", groupId = "bzba_extend_yz_group")
//    public void topic(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
////        System.out.println("testGroupContent  ,  top: ->" + topic);
////        System.out.println(record.value());
////        String str = JSON.toJSONString();
//        try {
//            jsonParse(record.value().toString());
//            addLog(record.value().toString(), topic, 0, null);
//        } catch (Exception e) {
//            log.error("异常信息:{}", e.toString());
//            addLog(record.value().toString(), topic, 1, e.toString());
//        }
//        ack.acknowledge();
//    }

    private void checkUser(LedyUserSimple ledyUserSimple) {
        LedyUserSimple qUser = new LedyUserSimple();
        qUser.setUserCode(ledyUserSimple.getUserCode());
        List<LedyUserSimple> qUserList = simpleService.selectLedyUserSimpleList(qUser);
        if (qUserList.size() == 0) {
            simpleService.insertLedyUserSimple(ledyUserSimple);
        }
    }

    private void addLog(String str, String topic, Integer status, String err) {
        SysOperLog log = new SysOperLog();
        log.setJsonResult(StringUtils.substring(str, 0, 5000));
        log.setBusinessType(0);
        log.setOperatorType(0);
        log.setStatus(status);
        log.setMethod("topic");
        log.setRequestMethod("kafka");
        log.setOperParam(topic);
        log.setErrorMsg(StringUtils.substring(err, 0, 5000));
        logService.insertOperlog(log);
    }

    @Transactional
    public void jsonParse(String str) throws Exception {
        BacFeeParam bacFeeParam = JSONUtil.toBean(str, BacFeeParam.class);
//            JSONObject json = JSONObject.parseObject(str);
        LedyBacFee ledyBacFee = JSONUtil.toBean(str, LedyBacFee.class);
//            LedyBacFee ledyBacFee = new LedyBacFee();
//            ledyBacFee.setRecordCode(json.getString("recordCode"));
//            ledyBacFee.setCaseCode(json.getString("caseCode"));
//            ledyBacFee.setRegisterNumber(json.getString("registerNumber"));
//            ledyBacFee.setGroupNumber(json.getJSONArray("groupNumber").toJSONString());
//            LedyUserSimple ledyUserClient = json.getObject("operator", LedyUserSimple.class);
//            checkUser(ledyUserClient);
//            ledyBacFee.setOperator(ledyUserClient.getUserCode());
//            LedyUserSimple acceptSecretary = json.getObject("acceptSecretary", LedyUserSimple.class);
//            checkUser(acceptSecretary);
//            ledyBacFee.setAcceptSecretary(acceptSecretary.getUserCode());
//            LedyUserSimple registerSecretary = json.getObject("registerSecretary", LedyUserSimple.class);
//            checkUser(registerSecretary);
//            ledyBacFee.setRegisterSecretary(registerSecretary.getUserCode());
//            LedyUserSimple handleSecretary = json.getObject("handleSecretary", LedyUserSimple.class);
//            checkUser(handleSecretary);
//            ledyBacFee.setHandleSecretary(handleSecretary.getUserCode());
//            LedyUserSimple lockedHandleSecretary = json.getObject("lockedHandleSecretary", LedyUserSimple.class);
//            checkUser(lockedHandleSecretary);
//            ledyBacFee.setLockedHandleSecretary(lockedHandleSecretary.getUserCode());
//            ledyBacFee.setEapRecordCode(json.getString("eapRecordCode"));
//            ledyBacFee.setRecordSchema(json.getString("recordSchema"));
        ledyBacFee.setRegisterSecretary("");
        ledyBacFee.setAcceptSecretary("");
        ledyBacFee.setHandleSecretary("");
        ledyBacFee.setLockedHandleSecretary("");
        if (ledyBacFee.getRecordSchema().equals("feeCheckIn")) {
//                LedyFeeCheckin recordDetail = json.getObject("recordDetail", LedyFeeCheckin.class);
            LedyFeeCheckin recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyFeeCheckin.class);
            if (recordDetail.getStatus() == 1) {
                BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
//                if("[1][6][0]".contains("["+ recordDetail.getClaimType() + "]")){
//                    recordDetail.setPayers(ledyBacFee.getp);
//                }else if("[2][3][7]".contains("["+ recordDetail.getClaimType() + "]")){
//
//                }else if("[4][5][8]".contains("["+ recordDetail.getClaimType() + "]")){
//
//                }
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setReceiptCodes("");
                recordDetail.setDocCodes("");
                recordDetail.setCheckinDocs("");
                recordDetail.setFallbackUser("");
                recordDetail.setConfirmUser("");
                recordDetail.setArbitratorList("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                checkinService.insertLedyFeeCheckin(recordDetail);
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());

            }
        } else if (ledyBacFee.getRecordSchema().equals("feeRefund")) {
//                LedyFeeRefund recordDetail = json.getObject("recordDetail", LedyFeeRefund.class);
            LedyFeeRefund recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyFeeRefund.class);
            if (recordDetail.getStatus() == 2) {
                BacFeeRefund bacFeeRefund = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeRefund.class);
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setLitigants(bacFeeRefund.getLitigants().stream().map(BacFeeRefund.LitigantsBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setLitigants(StringUtils.substring(recordDetail.getLitigants(), 0, 100));
                recordDetail.setRefundDocs("");
                recordDetail.setRefundOperateUser("");
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setSubmitFinanceUser("");
                recordDetail.setRefundAccount("");
                recordDetail.setReceiptCodes("");
                recordDetail.setDocCodes("");
                recordDetail.setOfficialDocCodes("");
                recordDetail.setStatData("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                refundService.insertLedyFeeRefund(recordDetail);
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());

            }
        } else if (ledyBacFee.getRecordSchema().equals("outerFeeCollect")) {
//                LedyOuterFeeCollect recordDetail = json.getObject("recordDetail", LedyOuterFeeCollect.class);
            LedyOuterFeeCollect recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyOuterFeeCollect.class);
            if (recordDetail.getStatus() == 1) {
                if ("[3][1][0]".contains("[" + recordDetail.getFeeType() + "]")) {
                    BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                    recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                            .collect(Collectors.joining(",")));
                    recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
                    recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                    recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                    recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                    recordDetail.setApplyUser("");
                    recordDetail.setApproveUser("");
                    recordDetail.setFeeDocs("");
                    recordDetail.setOutFeePayHistory("");
                    recordDetail.setCollector("");
                    LedyBacFee ledyBacFeeSerch = new LedyBacFee();
                    ledyBacFeeSerch.setRecordCode(ledyBacFee.getRecordCode());
                    List<LedyBacFee> ledyBacFeeList = ledyBacFeeService.selectLedyBacFeeList(ledyBacFeeSerch);
                    if (ledyBacFeeList != null && ledyBacFeeList.size() > 0) {
                        recordDetail.setId(Long.parseLong(ledyBacFeeList.get(0).getRecordDetail()));
                        collectService.updateLedyOuterFeeCollect(recordDetail);
                    } else {
                        collectService.insertLedyOuterFeeCollect(recordDetail);
                        ledyBacFee.setRecordDetail(recordDetail.getId().toString());
                        ledyBacFeeService.insertLedyBacFee(ledyBacFee);
                    }
                }
            }
        } else if (ledyBacFee.getRecordSchema().equals("outerFeePay")) {
            LedyOuterFeePay recordDetail = JSONUtil.toBean(ledyBacFee.getRecordDetail(), LedyOuterFeePay.class);
            if (recordDetail.getFeeStatus() == 2 || recordDetail.getFeeStatus() == 3) {
                BacFeeCheckin bacFeeCheckin = JSONUtil.toBean(ledyBacFee.getRecordDetail(), BacFeeCheckin.class);
                recordDetail.setPayers(bacFeeCheckin.getPayers().stream().map(BacFeeCheckin.PayersBean::getRealName)
                        .collect(Collectors.joining(",")));
                recordDetail.setPayers(StringUtils.substring(recordDetail.getPayers(), 0, 100));
                recordDetail.setAcceptNumber(ledyBacFee.getAcceptNumber());
                recordDetail.setRegisterNumber(ledyBacFee.getRegisterNumber());
                recordDetail.setOperator(bacFeeParam.getOperator().getRealName());
                recordDetail.setApplyUser("");
                recordDetail.setApproveUser("");
                recordDetail.setFeeDocs("");
                recordDetail.setAttachFiles("");
                recordDetail.setFeeListArray("");
                ledyBacFee.setRecordDetail("");
                ledyBacFeeService.insertLedyBacFee(ledyBacFee);
//                List<LedyFeePayDetail> recordPayDetail = JSONUtil.toBean(recordDetail.getDetails(), List<LedyFeePayDetail>.class);
                if (recordDetail.getDetails() != null && recordDetail.getDetails().size() > 0) {
                    recordDetail.getDetails().forEach(item -> {
                        LedyOuterFeePay recordDetails = new LedyOuterFeePay();
                        BeanUtil.copyProperties(recordDetail, recordDetails);
                        recordDetails.setPayers(StringUtils.substring(item.getRecordDetail().getPayers(), 0, 100));
                        recordDetails.setAmount(item.getPay());
                        recordDetails.setDetails(null);
                        payService.insertLedyOuterFeePay(recordDetails);
                    });
                } else {
                    recordDetail.setDetails(null);
                    payService.insertLedyOuterFeePay(recordDetail);
                }
                ledyBacFee.setRecordDetail(recordDetail.getId().toString());
            }
        }
//            ledyBacFee.setStatus(json.getLongValue("status"));
//            ledyBacFee.setInsertTime(json.getDate("insertTime"));
//            ledyBacFee.setUpdateTime(json.getDate("updateTime"));

    }
}

